package crm.viewframework;

import java.awt.Component;
import java.util.Vector;

import javax.swing.JComboBox;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JTextField;

public class Validater {
	private JPanel panel;
	private Vector<Component> componentsV;
	
	public Validater(JPanel panel)
	{
		this.panel = panel;
	    componentsV=new Vector<Component>();
		getComponentsForValidtion();
	}
	
	
	
	
	
	
	/*
	 * The method checks for improper conditions in JtextField and JcomboBox
	 */
	
	public String validateForEmpty()
	
	 {

		String message ="";
		for(Component x:componentsV)
		{
		
		if(x instanceof JTextField)
		{
			JTextField textField = (JTextField) x;
			String text=textField.getText();
			text=text.trim();
			
			if(text.equals(""))
				message = message+"Fill Empty Field"+"\n";
		}
		
		if(x instanceof JComboBox)
		{
			JComboBox comboBox = (JComboBox) x;
			String text=comboBox.getSelectedItem().toString();
			text = text.toUpperCase();
			text=text.trim();
			
			if(text.contains("SELECT"))
				message = message+"Some Items are not Selected"+"\n";
		}
		
		if(x instanceof JTextArea)
		{
			JTextArea textArea = (JTextArea) x;
			String text=textArea.getText();
			text=text.trim();
			if(text.equals(""))
				return "Errors in Form!";
		}
		
		}
		return "";
		
	}
	
	
	/*
	 * Very Important method. If you have to add a new component for validation 
	 * please add the type in If
	 */
	
	private void getComponentsForValidtion()
	{
		Component[] components=panel.getComponents();
		for(Component c:components)
		{
			if (c instanceof JTextField || c instanceof JComboBox || c instanceof JTextArea)
				componentsV.add(c);
				
		}
		
	}
	
	public void refresh()
	{
		for(Component x:componentsV)
		{
		if(x instanceof JTextField)
		{
			
			((JTextField) x).setText("");
		}
		
		if(x instanceof JComboBox)
		{
			JComboBox comboBox = (JComboBox) x;
			comboBox.setSelectedIndex(0);
		}
		
		if(x instanceof JTextArea)
		{
			JTextArea textArea = (JTextArea) x;  
			textArea.setText("");
		}
		}
	}

}
